package com.lujieni.springbootsecurity.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lujieni.springbootsecurity.dao.UserMapper;
import com.lujieni.springbootsecurity.po.LoginUser;
import com.lujieni.springbootsecurity.po.UserDO;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Arrays;

/**
 * @Author：小鹿爱吃鱼
 * @Date: 2025/5/29 10:33
 * @Description:
 */
@RequiredArgsConstructor
public class UserDetailServiceImpl implements UserDetailsService {

    private final UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        /**
         *  未配置 PasswordEncoder 时，可以在 密码前拼接上 {noop}，防止出错
         *  There is no PasswordEncoder mapped for the id "null"
         */
        UserDO result = userMapper.selectOne(new LambdaQueryWrapper<UserDO>().eq(UserDO::getUserName, userName));
        // 用户名没找到的话必须抛一下异常,异常会被ExceptionTranslationFilter捕获交给handler处理
        if(result == null) {
            throw new UsernameNotFoundException("");
        }
        return new LoginUser(result, Arrays.asList("kuku", "haha"));
    }
}
